package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    //进入controller之前先进行身份校验

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取当前用户信息
        Employee employee = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);

        if (employee != null) {
            //如果有值，说明身份合法，直接放行
            //将用户信息保存到ThreadLocal
            EmployeeHolder.set(employee);
            return true;
        } else {
            //如果没值返回错误信息
            log.info("用户身份不合法");

            //返回错误信息，前端拿到后跳转到登录页面
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            String json = new ObjectMapper().writeValueAsString(resultInfo);

            response.getWriter().write(json);
            return false;
        }
    }

    //当请求离开服务器的时候，移除掉ThreadLocal中的对象

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
